package com.leyou.sms.mq;

import com.gitee.yongzhuzl.commonutil.util.empty.EmptyUtil;
import com.gitee.yongzhuzl.commonutil.util.json.JsonTool;
import com.leyou.sms.config.SmsAlyProperties;
import com.leyou.sms.utils.SmsAlyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * description: 阿里云短信监听器
 * @author 朱正磊
 * @date 2021-04-15 18:10:10
 */
@Slf4j
@Component
public class SmsAlyListener {

    @Resource
    private SmsAlyUtils smsAlyUtils;

    @Resource
    private SmsAlyProperties smsAlyProperties;

    /**
     * description: 监听发送阿里云短信验证码
     * @author 朱正磊
     * @date 2021-04-15 18:15:10
     * @param msg 消息内容
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sms.aly.verify.code.queue", durable = "true"),
            exchange = @Exchange(name = "ly.sms.aly.exchange", type = ExchangeTypes.TOPIC),
            key = "sms.aly.verify.code"
    ))
    public void sendSmsAly(Map<String, String> msg) {
        if (EmptyUtil.isEmpty(msg)) {
            // 如果消息内容为空，直接返回什么都不做
            return;
        }
        // 手机号码（先获取再删除）
        String phoneNumber = msg.remove("phoneNumber");
        if (EmptyUtil.isEmpty(phoneNumber)) {
            // 如果手机号码为空，直接返回什么都不做
            return;
        }
        // 验证码（需要是json格式）
        String code = JsonTool.objectToJson(msg);
        // 处理消息，发送阿里云短信
        smsAlyUtils.sendSmsAly(phoneNumber, smsAlyProperties.getSignName(),
                smsAlyProperties.getVerifyCodeTemplate(), code);
    }

}
